package top;

/**
 * @author chenyw
 * @date 2022/7/11 21:04
 * @description   被围绕的区域
 *
 *      感染法，先遍历边界上的所有o，将其及与其相连的所有o变为其他字符。剩下的o则为需要变为x的
 *      妙啊
 *
 */
public class Top130solve {
    public void solve(char[][] board) {
        if (board == null || board.length == 0 || board[0].length == 0) {
            return;
        }
        int m = board.length;
        int n = board[0].length;
        for (int i = 0; i < m; i++) {
            dfs(board, i, 0);
            dfs(board, i, n - 1);
        }
        for (int i = 0; i < n; i++) {
            dfs(board, 0, i);
            dfs(board, m - 1, i);
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                //需要先改 O，再改 -
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                }
                if (board[i][j] == '-') {
                    board[i][j] = 'O';
                }
            }
        }
        return;
    }

    private void dfs(char[][] board, int i, int j) {
        if (i >= board.length || j >= board[0].length || i < 0 || j < 0 || board[i][j] != 'O') {
            return;
        }
        board[i][j] = '-';
        dfs(board, i + 1, j);
        dfs(board, i - 1, j);
        dfs(board, i, j + 1);
        dfs(board, i, j - 1);
        return;
    }
}
